package com.blog.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.blog.model.User;
import com.blog.service.UserService;
import com.blog.util.MD5Util;

@Controller
@RequestMapping("/user")
public class UserController{
	private UserService userService;
	
	@RequestMapping(value = "/doLogin")
	public ModelAndView doLogin(User user,HttpServletRequest request,HttpServletResponse response){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("/login/login");
		if(user == null){
			return modelAndView;
		}
		System.out.println(JSON.toJSONString(user));
		HttpSession session = request.getSession();
		user.setPassword(MD5Util.getMD5String(user.getPassword()));
		System.out.println(JSON.toJSONString(user));
		// 查询用户是否存在
		User newUser = userService.getUserByLoginNameAndPassword(user.getLoginName(), user.getPassword());
		System.out.println(newUser);
		if (newUser != null) {
			// 设置7天免登录
			//String user_account = newUser.getUser_account();
			//String user_password = newUser.getUser_password();

//			Integer expiry = 24 * 60 * 60 * 7;
//			response.addCookie(CookiesUtil.addCookies("user_account",
//					newUser.getLoginname(), expiry));
			System.out.println("login success");
			session.setAttribute("user", newUser);
			modelAndView.setViewName("index");
		}else{
			System.out.println("login error");
		}
		
		return modelAndView;
	}
	
	@RequestMapping("/doRegister")
	public ModelAndView doRegister(User user,HttpServletRequest request,HttpServletResponse response){
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.setViewName("/login/login");
		if(user == null){
			return modelAndView;
		}
		System.out.println(JSON.toJSONString(user));
		HttpSession session = request.getSession();
		user.setPassword(MD5Util.getMD5String(user.getPassword()));
		
		//查重
		User haveUser = userService.getUserByLoginNameAndPassword(user.getLoginName(), user.getPassword());
		if(haveUser == null){
			System.out.println(JSON.toJSONString(user));
			userService.addUser(user);
			System.out.println("register success");
			modelAndView.setViewName("index");
			
			return modelAndView;
		}
		System.out.println("have own user!");
		
		return modelAndView;
	}
	
	@RequestMapping("/login")
	public ModelAndView login(){
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.setViewName("/login/login");
		
		return modelAndView;
	}
	

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
}
